<template>
  <div class="outbound-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>出库单管理</h2>
      <p>管理出库单信息，支持查询、导出、审核等操作</p>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="出库时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
          <span style="margin: 0 8px">至</span>
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        
        <el-form-item label="出库单号">
          <el-input
            v-model="searchForm.outboundOrderNumber"
            placeholder="请输入出库单号"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="出库类型">
          <el-select
            v-model="searchForm.outboundType"
            placeholder="请选择出库类型"
            style="width: 200px"
            clearable
          >
            <el-option label="销售出库" value="销售出库" />
            <el-option label="生产领料" value="生产领料" />
            <el-option label="其他出库" value="其他出库" />
          </el-select>
        </el-form-item>
        
                 <el-form-item label="审核状态">
           <el-select
            v-model="searchForm.approval"
             placeholder="请选择审核状态"
             style="width: 200px"
             clearable
           >
             <el-option label="待审核" value="待审核" />
             <el-option label="审核通过" value="审核通过" />
             <el-option label="驳回" value="驳回" />
           </el-select>
         </el-form-item>
        
        <el-form-item label="创建人">
          <el-input
            v-model="searchForm.createdBy"
            placeholder="请输入创建人"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>出库单列表</h3>
          <span class="total-count">共 {{ total }} 条记录</span>
        </div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
        </div>
      </div>

             <el-table
         :data="tableData"
         v-loading="loading"
         stripe
         border
         style="width: 100%"
         max-height="400"
         @selection-change="handleSelectionChange"
       >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="outboundId" label="出库ID" width="100" />
        
        <el-table-column prop="outboundOrderNumber" label="出库单号" width="150" />
        
        <el-table-column prop="outboundType" label="出库类型" width="120" />
        
        <el-table-column prop="outboundTime" label="出库时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.outboundTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="approval" label="审核状态" width="120">
           <template #default="{ row }">
            <el-tag :type="getApprovalStatusType(row.approval)">
              {{ getApprovalStatusText(row.approval) }}
             </el-tag>
           </template>
         </el-table-column>
         
         <el-table-column prop="bkThumbnail" label="缩略图" width="120">
           <template #default="{ row }">
            <div class="thumbnail-container">
              <el-image
                v-if="row.bkThumbnail"
               :src="getImageUrl(row.bkThumbnail)" 
                :preview-src-list="[getImageUrl(row.bkThumbnail)]"
                fit="cover"
                style="width: 50px; height: 50px; border-radius: 4px;"
                :initial-index="0"
                @error="(e: any) => console.error('图片加载失败:', row.bkThumbnail, e)"
              />
              <span v-else class="no-image">无图片</span>
             </div>
           </template>
         </el-table-column>
         
        <el-table-column prop="annex" label="附件" width="120">
          <template #default="{ row }">
            <div class="annex-container">
              <el-button
                v-if="row.annex"
                type="primary"
                size="small"
                class="annex-download-btn"
                @click="handleDownloadAnnex(row.annex)"
              >
                <el-icon><Download /></el-icon>
                下载
              </el-button>
              <span v-else class="no-annex">无附件</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="remarks" label="备注" width="200" show-overflow-tooltip />
         
        <el-table-column prop="createdBy" label="创建人" width="120" />
        
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        
         <el-table-column label="操作" width="350" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
                         <el-button 
               type="success" 
               size="small" 
               @click="handleApprove(row)"
              :disabled="row.approval === '审核通过'"
             >
               审核
             </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 出库单产品明细 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>产品明细列表</h3>
          <span class="total-count">共 {{ allProductDetails.length }} 条记录</span>
        </div>
      </div>

             <el-table
         :data="allProductDetails"
         v-loading="detailsLoading"
         stripe
         border
         style="width: 100%"
         max-height="300"
         @selection-change="handleDetailSelectionChange"
       >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productName" label="*产品名称" width="150" sortable />
                 <el-table-column prop="productNumber" label="*产品编号" width="150" sortable />
         <el-table-column prop="inventoryUnit" label="*库存单位" width="100" sortable />
         <el-table-column prop="productSpecification" label="产品规格" width="120" />
         <el-table-column prop="maxInventory" label="最大库存" width="100" sortable />
         <el-table-column prop="minInventory" label="最小库存" width="100" sortable />
         <el-table-column prop="safetyInventory" label="安全库存" width="100" sortable />
         <el-table-column prop="outboundQuantity" label="*出库数量" width="120" sortable>
           <template #default="{ row }">
             <el-input-number
               v-model="row.outboundQuantity"
               :min="1"
               :precision="0"
               size="small"
               style="width: 100px"
             />
           </template>
         </el-table-column>
        <el-table-column prop="inventoryQuantity" label="当前库存" width="120" sortable />
        <el-table-column prop="createdBy" label="创建人" width="120" sortable />
        <el-table-column prop="createdTime" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 明细分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="detailsCurrentPage"
          v-model:page-size="detailsPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="allProductDetails.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleDetailSizeChange"
          @current-change="handleDetailCurrentChange"
        />
      </div>
    </el-card>

     <!-- 新增对话框 -->
    <el-dialog
       v-model="addDialogVisible"
       title="新增出库单"
       width="900px"
      :close-on-click-modal="false"
       class="add-dialog"
    >
          <el-form
         ref="addFormRef"
         :model="addForm"
         :rules="addFormRules"
            label-width="120px"
         class="add-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出库单号" prop="outboundOrderNumber">
                  <el-input
                 v-model="addForm.outboundOrderNumber"
                 placeholder="请输入出库单号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出库类型" prop="outboundType">
                  <el-select
                 v-model="addForm.outboundType"
                 placeholder="请选择出库类型"
                    style="width: 100%"
                  >
                    <el-option label="销售出库" value="销售出库" />
                    <el-option label="生产领料" value="生产领料" />
                    <el-option label="其他出库" value="其他出库" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出库时间" prop="outboundTime">
                  <el-date-picker
                     v-model="addForm.outboundTime"
                    type="datetime"
                    placeholder="请选择出库时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                 </el-form-item>
               </el-col>
            </el-row>
            
         <el-form-item label="备注" prop="remarks">
                   <el-input
             v-model="addForm.remarks"
             type="textarea"
             :rows="3"
             placeholder="请输入备注..."
                   />
                 </el-form-item>
         
         <!-- 缩略图上传 -->
         <el-form-item label="缩略图">
                   <el-upload
               ref="thumbnailUploadRef"
               :action="`http://localhost:5265/api/FileUpload/UploadOutboundThumbnail`"
               :headers="uploadHeaders"
                     :on-success="handleThumbnailSuccess"
               :on-error="handleThumbnailError"
                     :before-upload="beforeThumbnailUpload"
               :show-file-list="false"
               :data="{ type: 'thumbnail' }"
               name="file"
               accept="image/*"
             class="thumbnail-upload"
           >
             <div class="upload-area">
               <el-image
                 v-if="addForm.bkThumbnail"
                 :src="getImageUrl(addForm.bkThumbnail)"
                 fit="cover"
                 style="width: 100px; height: 100px; border-radius: 8px;"
                 @error="(e: any) => console.error('新增对话框图片加载失败:', addForm.bkThumbnail, e)"
               />
               <div v-else class="upload-placeholder">
                 <el-icon><Camera /></el-icon>
                 <span>点击上传缩略图</span>
               </div>
             </div>
                   </el-upload>
                 </el-form-item>
             
         <!-- 附件上传 -->
         <el-form-item label="附件">
                                       <el-upload
                ref="annexUploadRef"
                :action="`http://localhost:5265/api/FileUpload/UploadOutboundAnnex`"
                :headers="uploadHeaders"
                :on-success="handleAnnexSuccess"
                :on-error="handleAnnexError"
                :before-upload="beforeAnnexUpload"
                :show-file-list="false"
                :data="{ type: 'annex' }"
                name="file"
                accept=".pdf,.doc,.docx,.xls,.xlsx,.txt"
                class="annex-upload"
           >
             <el-button type="primary">
               <el-icon><Upload /></el-icon>
               上传附件
             </el-button>
                   </el-upload>
           <div v-if="addForm.annex" class="annex-info">
             <el-icon><Document /></el-icon>
             <span>已上传: {{ getFileName(addForm.annex) }}</span>
           </div>
                 </el-form-item>
         
         <!-- 产品选择 -->
         <el-form-item label="产品选择">
           <div class="product-selection">
            <el-button type="primary" @click="handleSelectProduct">
              <el-icon><Plus /></el-icon>
              选择产品
            </el-button>
             <el-button type="danger" @click="handleRemoveSelectedProducts" :disabled="!selectedProductRows.length">
              <el-icon><Delete /></el-icon>
               删除选中
            </el-button> 
          </div>

          <el-table
             :data="addForm.productDetails"
            border
            style="width: 100%"
             max-height="300"
             @selection-change="handleProductSelectionChange"
          >
            <el-table-column type="selection" width="55" />
             <el-table-column prop="productName" label="产品名称" width="150" />
             <el-table-column prop="productNumber" label="产品编号" width="150" />
             <el-table-column prop="outboundQuantity" label="出库数量" width="120">
               <template #default="{ row }">
                 <el-input-number
                   v-model="row.outboundQuantity"
                   :min="1"
                   :precision="0"
                   size="small"
                   style="width: 100px"
                 />
               </template>
             </el-table-column>
             <el-table-column prop="inventoryUnit" label="单位" width="80" />
             <el-table-column prop="inventoryQuantity" label="当前库存" width="100" />
          </el-table>
         </el-form-item>
       </el-form>
      
      <template #footer>
         <div class="add-footer">
           <el-button @click="addDialogVisible = false">取消</el-button>
           <el-button type="primary" @click="handleConfirmAdd" :loading="addLoading">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

     <!-- 产品选择对话框 -->
    <el-dialog
       v-model="productSelectDialogVisible"
      title="选择产品"
       width="1000px"
      :close-on-click-modal="false"
       class="product-select-dialog"
    >
        <div class="product-search">
          <el-input
            v-model="productSearchKeyword"
           placeholder="搜索产品名称或编号"
            style="width: 300px"
            clearable
            @input="handleProductSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-table
          :data="filteredProducts"
          v-loading="productsLoading"
          stripe
          border
          style="width: 100%"
          max-height="400"
         @selection-change="handleProductTableSelectionChange"
        >
          <el-table-column type="selection" width="55" />
         <el-table-column prop="productName" label="产品名称" width="200" />
         <el-table-column prop="productNumber" label="产品编号" width="150" />
         <el-table-column prop="productSpecification" label="产品规格" width="150" />
          <el-table-column prop="inventoryUnit" label="库存单位" width="100" />
         <el-table-column prop="maxInventory" label="最大库存" width="100" />
         <el-table-column prop="minInventory" label="最小库存" width="100" />
         <el-table-column prop="safetyInventory" label="安全库存" width="100" />
         <el-table-column prop="inventoryQuantity" label="当前库存" width="100" />
        </el-table>
       
       <template #footer>
         <div class="product-select-footer">
           <el-button @click="productSelectDialogVisible = false">取消</el-button>
           <el-button type="primary" @click="handleConfirmProductSelection">
             <el-icon><Check /></el-icon>
             确认选择
           </el-button>
      </div>
       </template>
     </el-dialog>

     <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑出库单"
      width="800px"
      :close-on-click-modal="false"
      class="edit-dialog"
    >
          <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
            label-width="120px"
        class="edit-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出库单号" prop="outboundOrderNumber">
                  <el-input
                v-model="editForm.outboundOrderNumber"
                placeholder="请输入出库单号"
                :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出库类型" prop="outboundType">
                  <el-select
                v-model="editForm.outboundType"
                placeholder="请选择出库类型"
                    style="width: 100%"
                  >
                    <el-option label="销售出库" value="销售出库" />
                    <el-option label="生产领料" value="生产领料" />
                    <el-option label="其他出库" value="其他出库" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
                         <el-row :gutter="20">
               <el-col :span="12">
                 <el-form-item label="出库时间" prop="outboundTime">
                   <el-date-picker
                     v-model="editForm.outboundTime"
                     type="datetime"
                     placeholder="请选择出库时间"
                     format="YYYY-MM-DD HH:mm:ss"
                     value-format="YYYY-MM-DD HH:mm:ss"
                     style="width: 100%"
                   />
                 </el-form-item>
               </el-col>
             </el-row>
             
             <!-- 缩略图上传 -->
             <el-form-item label="缩略图">
                               <el-upload
                  ref="editThumbnailUploadRef"
                  :action="`http://localhost:5265/api/FileUpload/UploadOutboundThumbnail`"
                  :headers="uploadHeaders"
                  :on-success="handleThumbnailSuccess"
                  :on-error="handleThumbnailError"
                  :before-upload="beforeThumbnailUpload"
                  :show-file-list="false"
                  :data="{ type: 'thumbnail' }"
                  name="file"
                  accept="image/*"
                  class="thumbnail-upload"
               >
                 <div class="upload-area">
                   <el-image
                     v-if="editForm.bkThumbnail"
                     :src="getImageUrl(editForm.bkThumbnail)"
                     fit="cover"
                     style="width: 100px; height: 100px; border-radius: 8px;"
                     @error="(e: any) => console.error('编辑对话框图片加载失败:', editForm.bkThumbnail, e)"
                   />
                   <div v-else class="upload-placeholder">
                     <el-icon><Camera /></el-icon>
                     <span>点击上传缩略图</span>
                   </div>
                 </div>
               </el-upload>
             </el-form-item>
             
             <!-- 附件上传 -->
             <el-form-item label="附件">
                                                                 <el-upload
                    ref="editAnnexUploadRef"
                    :action="`http://localhost:5265/api/FileUpload/UploadOutboundAnnex`"
                    :headers="uploadHeaders"
                    :on-success="handleAnnexSuccess"
                    :on-error="handleAnnexError"
                    :before-upload="beforeAnnexUpload"
                    :show-file-list="false"
                    :data="{ type: 'annex' }"
                    name="file"
                    accept=".pdf,.doc,.docx,.xls,.xlsx,.txt"
                    class="annex-upload"
                 >
                 <el-button type="primary">
                   <el-icon><Upload /></el-icon>
                   上传附件
                 </el-button>
               </el-upload>
               <div v-if="editForm.annex" class="annex-info">
                 <el-icon><Document /></el-icon>
                 <span>已上传: {{ getFileName(editForm.annex) }}</span>
               </div>
             </el-form-item>
             
             <el-form-item label="备注" prop="remarks">
               <el-input
            v-model="editForm.remarks"
                 type="textarea"
                 :rows="3"
            placeholder="请输入备注..."
               />
             </el-form-item>
        
        <!-- 产品明细表格 -->
        <el-form-item label="产品明细">
          <div class="product-selection">
            <el-button type="primary" @click="handleEditSelectProduct">
              <el-icon><Plus /></el-icon>
              选择产品
            </el-button>
            <el-button type="danger" @click="handleEditRemoveSelectedProducts" :disabled="!selectedEditProductRows.length">
              <el-icon><Delete /></el-icon>
              删除选中
            </el-button>
          </div>
          
          <el-table
            :data="editForm.productDetails"
            border
            style="width: 100%"
            max-height="300"
            @selection-change="handleEditProductSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="productName" label="产品名称" width="150" />
            <el-table-column prop="productNumber" label="产品编号" width="150" />
            <el-table-column prop="outboundQuantity" label="出库数量" width="120">
               <template #default="{ row }">
                 <el-input-number
                   v-model="row.outboundQuantity"
                  :min="1"
                  :precision="0"
                   size="small"
                   style="width: 100px"
                 />
               </template>
             </el-table-column>
            <el-table-column prop="inventoryUnit" label="单位" width="80" />
            <el-table-column prop="inventoryQuantity" label="当前库存" width="100" />
          </el-table>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="edit-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmEdit" :loading="editLoading">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

         <!-- 审核对话框 -->
     <el-dialog
       v-model="approvalDialogVisible"
       title="审核"
       width="500px"
       :close-on-click-modal="false"
       class="approval-dialog"
     >
       <!-- 信息提示栏 -->
       <div class="approval-info-bar">
         <el-icon><InfoFilled /></el-icon>
         <span>当前选中【{{ selectedRows.length }}】条记录待审核..</span>
       </div>
       
       <!-- 审核选项 -->
       <div class="approval-options">
         <div class="approval-label">审批:</div>
        <el-radio-group v-model="approvalForm.approval" class="approval-radio-group">
            <el-radio label="审核通过">审核通过</el-radio>
            <el-radio label="驳回">驳回</el-radio>
          </el-radio-group>
       </div>
       
       <!-- 备注输入 -->
       <div class="approval-remarks">
         <el-input
           v-model="approvalForm.remarks"
           type="textarea"
           :rows="6"
           placeholder="请输入备注..."
           resize="both"
           class="remarks-textarea"
         />
       </div>
       
       <template #footer>
         <div class="approval-footer">
           <el-button type="primary" @click="handleConfirmApproval" :loading="approvalLoading">
             <el-icon><Check /></el-icon>
             审批
           </el-button>
         </div>
       </template>
     </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Download, Plus, InfoFilled, Delete, Upload, Close, Check, Camera, Picture } from '@element-plus/icons-vue'
import { 
  getAllOutboundOrders, 
  searchOutboundOrders, 
  exportOutboundOrders, 
  addOutboundOrder,
  updateOutboundOrder,
  deleteOutboundOrder,
  getProducts,
  getOutboundOrderDetails,
  getOutboundProductDetails,
  getOutboundProductDetailsByOrderNumber,
  updateApprovalStatus,
  getApprovalStatusOptions,
  saveOutboundOrderDetails,
  uploadOutboundThumbnail,
  type OutboundOrder, 
  type SearchParams,
  type AddOutboundOrderParams,
  type Product,
  type OutboundOrderDetail
} from '@/api/outboundOrder'
import { exportToCSVOutboundOrder, exportToExcelOutboundOrder } from '@/utils/excelExport'

// 配置后端服务器地址（用于图片访问）
const BACKEND_SERVER_URL = 'http://localhost:5265'

// 获取token的计算属性
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`,
  // 不设置Content-Type，让浏览器自动设置multipart/form-data
}))

// 获取图片URL的函数
const getImageUrl = (imagePath: string) => {
  if (!imagePath) return ''
  
  // 如果已经是完整URL，直接返回
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath
  }
  
  // 如果以/开头，直接拼接
  if (imagePath.startsWith('/')) {
    return `${BACKEND_SERVER_URL}${imagePath}`
  }
  
  // 否则添加/前缀
  return `${BACKEND_SERVER_URL}/${imagePath}`
}

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const approvalLoading = ref(false)
const detailsLoading = ref(false)
const editLoading = ref(false)
const addLoading = ref(false)
const productsLoading = ref(false)
const tableData = ref<OutboundOrder[]>([])
const selectedRows = ref<OutboundOrder[]>([])
const selectedDetailRows = ref<OutboundOrderDetail[]>([])
const selectedProductRows = ref<OutboundOrderDetail[]>([])
const selectedProducts = ref<Product[]>([])
const selectedEditProductRows = ref<OutboundOrderDetail[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const detailsCurrentPage = ref(1)
const detailsPageSize = ref(20)
const total = ref(0)
const allProductDetails = ref<OutboundOrderDetail[]>([])
const allProducts = ref<Product[]>([])
const filteredProducts = ref<Product[]>([])
const productSearchKeyword = ref('')

// 对话框相关
const approvalDialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)
const productSelectDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const addFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive<SearchParams>({
  startTime: '',
  endTime: '',
  outboundOrderNumber: '',
  outboundType: '',
  approval: '',
  createdBy: ''
})

// 审核表单
const approvalForm = reactive({
  outboundId: 0,
  outboundOrderNumber: '',
  approval: '',
  remarks: '',
  modifiedBy: 'admin'
})

// 编辑表单
const editForm = reactive({
  outboundId: 0,
  outboundOrderNumber: '',
  outboundType: '',
  outboundTime: '',
  approval: '',
  remarks: '',
  bkThumbnail: '',
  annex: '',
  productDetails: [] as OutboundOrderDetail[]
})

// 编辑表单验证规则
const editFormRules: FormRules = {
  outboundType: [
    { required: true, message: '请选择出库类型', trigger: 'change' }
  ],
  outboundTime: [
    { required: true, message: '请选择出库时间', trigger: 'change' }
  ]
}

// 新增表单
const addForm = reactive({
  outboundOrderNumber: '',
  outboundType: '',
  outboundTime: '',
  approval: '待审核',
  remarks: '',
  bkThumbnail: '',
  annex: '',
  productDetails: [] as OutboundOrderDetail[]
})

// 新增表单验证规则
const addFormRules: FormRules = {
  outboundOrderNumber: [
    { required: true, message: '请输入出库单号', trigger: 'blur' }
  ],
  outboundType: [
    { required: true, message: '请选择出库类型', trigger: 'change' }
  ],
  outboundTime: [
    { required: true, message: '请选择出库时间', trigger: 'change' }
  ]
}

// 计算属性：是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.startTime || searchForm.endTime || searchForm.outboundOrderNumber || searchForm.outboundType || searchForm.approval || searchForm.createdBy
})

// 获取审核状态文本
const getApprovalStatusText = (status: string) => {
  if (!status || status.trim() === '' || status === null || status === undefined) {
    return '待审核'
  }
  
  const trimmedStatus = status.trim()
  
  switch (trimmedStatus) {
    case '待审核':
    case '0':
      return '待审核'
    case '审核通过':
    case '通过':
    case '1':
      return '审核通过'
    case '驳回':
    case '拒绝':
    case '2':
      return '驳回'
    default:
      return '待审核'
  }
}

// 获取审核状态标签类型
const getApprovalStatusType = (status: string) => {
  if (!status || status.trim() === '' || status === null || status === undefined) {
    return 'warning'
  }
  
  const trimmedStatus = status.trim()
  
  switch (trimmedStatus) {
    case '待审核':
    case '0':
      return 'warning'
    case '审核通过':
    case '通过':
    case '1':
      return 'success'
    case '驳回':
    case '拒绝':
    case '2':
      return 'danger'
    default:
      return 'warning'
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取数据
const fetchData = async (forceRefresh = false) => {
  loading.value = true
  try {
    let response
    
    if (hasSearchConditions.value) {
      response = await searchOutboundOrders(searchForm)
    } else {
      response = await getAllOutboundOrders(forceRefresh)
    }
    
    if (response.code === 200) {
      console.log('API返回的原始数据:', response.data)
      
      tableData.value = response.data.map((item: OutboundOrder) => {
        console.log('处理数据项:', {
          outboundId: item.outboundId,
          outboundOrderNumber: item.outboundOrderNumber,
          approval: item.approval,
          approvalType: typeof item.approval
        })
        
        return item
      })
      total.value = response.data.length
      console.log('数据刷新完成，当前表格数据:', tableData.value)
      
      if (!forceRefresh) {
      ElMessage.success('数据加载成功')
      }
    } else {
      ElMessage.error(response.msg || '数据加载失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1
  await fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    startTime: '',
    endTime: '',
    outboundOrderNumber: '',
    outboundType: '',
    approval: '',
    createdBy: ''
  })
  currentPage.value = 1
  fetchData()
}

// 导出
const handleExport = async () => {
  exportLoading.value = true
    try {
      const blob = await exportOutboundOrders(searchForm)
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
    link.download = `出库单_${new Date().toISOString().split('T')[0]}.xlsx`
      link.click()
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 新增
const handleAdd = () => {
  // 重置表单
  Object.assign(addForm, {
    outboundOrderNumber: '',
    outboundType: '',
    outboundTime: '',
    approval: '待审核',
    remarks: '',
    bkThumbnail: '',
    annex: '',
    productDetails: []
  })
  
  // 打开新增对话框
  addDialogVisible.value = true
}

// 下载附件
const handleDownloadAnnex = (annexPath: string) => {
  if (!annexPath) {
    ElMessage.warning('附件路径为空')
    return
  }
  
  console.log('下载附件路径:', annexPath)
  
  // 构建完整的下载URL
  let downloadUrl = ''
  if (annexPath.startsWith('http://') || annexPath.startsWith('https://')) {
    downloadUrl = annexPath
  } else if (annexPath.startsWith('/')) {
    downloadUrl = `${BACKEND_SERVER_URL}${annexPath}`
        } else {
    downloadUrl = `${BACKEND_SERVER_URL}/${annexPath}`
  }
  
  console.log('完整下载URL:', downloadUrl)
  
  const link = document.createElement('a')
  link.href = downloadUrl
  link.download = getFileName(annexPath)
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('开始下载附件')
}

// 获取文件名
const getFileName = (filePath: string) => {
  if (!filePath) return ''
  return filePath.split('/').pop() || ''
}

// 缩略图上传成功
const handleThumbnailSuccess = (response: any) => {
  console.log('缩略图上传响应:', response)
  console.log('响应数据结构:', {
    code: response.code,
    msg: response.msg,
    data: response.data,
    dataType: typeof response.data
  })
  
  if (response.code === 200 && response.data) {
    // 尝试多种可能的数据结构
    let imagePath = ''
    if (typeof response.data === 'string') {
      imagePath = response.data
    } else if (response.data.filePath) {
      imagePath = response.data.filePath
    } else if (response.data.path) {
      imagePath = response.data.path
    } else if (response.data.url) {
      imagePath = response.data.url
  } else {
      imagePath = response.data
    }
    
    console.log('设置的图片路径:', imagePath)
    
    // 根据当前激活的对话框设置相应的表单
    if (addDialogVisible.value) {
      addForm.bkThumbnail = imagePath
    } else if (editDialogVisible.value) {
      editForm.bkThumbnail = imagePath
    }
    
    ElMessage.success('缩略图上传成功')
  } else {
    ElMessage.error(response.msg || '缩略图上传失败')
  }
}

// 缩略图上传失败
const handleThumbnailError = (error: any) => {
  console.error('缩略图上传失败:', error)
  console.error('错误详情:', {
    status: error.status,
    statusText: error.statusText,
    response: error.response,
    message: error.message
  })
  ElMessage.error(`缩略图上传失败: ${error.message || '网络错误'}`)
}

// 缩略图上传前验证
const beforeThumbnailUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 附件上传成功
const handleAnnexSuccess = (response: any) => {
  console.log('附件上传响应:', response)
  console.log('响应详细信息:', {
    code: response.code,
    msg: response.msg,
    data: response.data,
    dataType: typeof response.data
  })
  
  if (response.code === 200 && response.data) {
    // 根据API返回的数据结构，可能需要调整
    const annexPath = response.data.filePath || response.data
    
    console.log('设置的附件路径:', annexPath)
    
    // 根据当前激活的对话框设置相应的表单
    if (addDialogVisible.value) {
      addForm.annex = annexPath
      console.log('设置到新增表单:', addForm.annex)
    } else if (editDialogVisible.value) {
      editForm.annex = annexPath
      console.log('设置到编辑表单:', editForm.annex)
    }
    
    ElMessage.success('附件上传成功')
          } else {
    console.error('附件上传失败:', response)
    ElMessage.error(response.msg || '附件上传失败')
  }
}

// 附件上传失败
const handleAnnexError = (error: any) => {
  console.error('附件上传失败:', error)
  console.error('错误详情:', {
    status: error.status,
    statusText: error.statusText,
    response: error.response,
    message: error.message,
    errorType: typeof error,
    errorKeys: Object.keys(error)
  })
  
  // 尝试获取更详细的错误信息
  let errorMessage = '网络错误'
  if (error.response && error.response.data) {
    console.error('服务器错误响应:', error.response.data)
    errorMessage = error.response.data.msg || error.response.data.message || '服务器错误'
  } else if (error.message) {
    errorMessage = error.message
  }
  
  ElMessage.error(`附件上传失败: ${errorMessage}`)
}

// 附件上传前验证
const beforeAnnexUpload = (file: File) => {
  console.log('附件上传验证:', {
    fileName: file.name,
    fileType: file.type,
    fileSize: file.size,
    fileExtension: '.' + file.name.split('.').pop()?.toLowerCase(),
    fileSizeMB: (file.size / 1024 / 1024).toFixed(2) + 'MB'
  })
  
  // 只检查文件扩展名，简化验证逻辑
  const allowedExtensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt']
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!allowedExtensions.includes(fileExtension)) {
    console.error('附件文件类型不支持:', fileExtension)
    ElMessage.error(`附件文件类型不支持! 支持的类型: PDF、Word(.doc/.docx)、Excel(.xls/.xlsx)、TXT文件`)
    return false
  }
  
  if (!isLt10M) {
    ElMessage.error('附件文件大小不能超过 10MB!')
    return false
  }
  
  console.log('附件验证通过，准备上传文件:', file.name)
  return true
}

// 选择产品
const handleSelectProduct = () => {
  productSelectDialogVisible.value = true
  // 加载产品数据
    fetchProducts()
  }

// 编辑对话框选择产品
const handleEditSelectProduct = () => {
  productSelectDialogVisible.value = true
  // 加载产品数据
  fetchProducts()
}
  
// 删除选中的产品
const handleRemoveSelectedProducts = () => {
  if (selectedProductRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的产品')
    return
  }
  
  const selectedIds = selectedProductRows.value.map(item => item.productId)
  addForm.productDetails = addForm.productDetails.filter(item => !selectedIds.includes(item.productId))
  selectedProductRows.value = []
  ElMessage.success('删除成功')
}

// 产品选择变化
const handleProductSelectionChange = (selection: OutboundOrderDetail[]) => {
  selectedProductRows.value = selection
}

// 编辑对话框产品选择变化
const handleEditProductSelectionChange = (selection: OutboundOrderDetail[]) => {
  selectedEditProductRows.value = selection
}

// 编辑对话框删除选中的产品
const handleEditRemoveSelectedProducts = () => {
  if (selectedEditProductRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的产品')
    return
  }
  
  const selectedIds = selectedEditProductRows.value.map(item => item.productId)
  editForm.productDetails = editForm.productDetails.filter(item => !selectedIds.includes(item.productId))
  selectedEditProductRows.value = []
  ElMessage.success('删除成功')
}

// 产品表格选择变化
const handleProductTableSelectionChange = (selection: Product[]) => {
  console.log('产品选择变化:', selection)
  selectedProducts.value = selection
}

// 产品搜索
const handleProductSearch = () => {
  if (!productSearchKeyword.value) {
    filteredProducts.value = allProducts.value
  } else {
    filteredProducts.value = allProducts.value.filter(product => 
      product.productName.includes(productSearchKeyword.value) ||
      product.productNumber.includes(productSearchKeyword.value)
    )
  }
}

// 确认产品选择
const handleConfirmProductSelection = () => {
  console.log('确认产品选择:', selectedProducts.value)
  console.log('当前新增表单产品明细:', addForm.productDetails)
  
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请先选择产品')
    return
  }
  
    // 将选中的产品转换为出库单明细格式
  const newProductDetails = selectedProducts.value.map(product => ({
    outboundOrderNumber: addForm.outboundOrderNumber || '',
    productId: product.productId || product.id,
    productName: product.productName,
    productNumber: product.productNumber,
    productSpecification: product.productSpecification,
    inventoryUnit: product.inventoryUnit,
    maxInventory: product.maxInventory,
    minInventory: product.minInventory,
    safetyInventory: product.safetyInventory,
    inventoryQuantity: product.current || product.num || 0, // 使用current或num字段作为当前库存
    outboundQuantity: 1, // 默认出库数量为1
    currentInventoryQuantity: product.current || product.num || 0
  }))
  
  console.log('转换后的产品明细:', newProductDetails)
  
  // 根据当前激活的对话框添加到相应的表单
  if (addDialogVisible.value) {
    addForm.productDetails.push(...newProductDetails)
    console.log('添加到新增表单的产品明细:', addForm.productDetails)
  } else if (editDialogVisible.value) {
    editForm.productDetails.push(...newProductDetails)
    console.log('添加到编辑表单的产品明细:', editForm.productDetails)
  }
  
  // 清空选择
  selectedProducts.value = []
  
  // 关闭对话框
  productSelectDialogVisible.value = false
  
  ElMessage.success(`成功添加 ${newProductDetails.length} 个产品`)
}

// 获取产品数据
const fetchProducts = async () => {
  productsLoading.value = true
  try {
    console.log('开始获取产品数据...')
    const response = await getProducts()
    console.log('产品数据响应:', response)
    
    if (response.code === 200) {
      allProducts.value = response.data
      filteredProducts.value = response.data
      console.log('产品数据加载成功，共', response.data.length, '个产品')
      
      if (response.data.length === 0) {
        ElMessage.warning('产品列表为空，请先添加产品数据')
      }
    } else {
      console.error('获取产品数据失败:', response.msg)
      ElMessage.error(response.msg || '获取产品数据失败')
    }
  } catch (error) {
    console.error('获取产品数据失败:', error)
    ElMessage.error('获取产品数据失败')
  } finally {
    productsLoading.value = false
  }
}

// 手动上传附件（备选方案）
const handleManualAnnexUpload = async (file: File) => {
  try {
    console.log('开始手动上传附件:', file.name)
    
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'annex')
    
    const response = await fetch('http://localhost:5265/api/FileUpload/UploadOutboundAnnex', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      },
      body: formData
    })
    
    const result = await response.json()
    console.log('手动上传结果:', result)
    
    if (result.code === 200) {
      const annexPath = result.data.filePath || result.data
      
      if (addDialogVisible.value) {
        addForm.annex = annexPath
      } else if (editDialogVisible.value) {
        editForm.annex = annexPath
      }
      
      ElMessage.success('附件上传成功')
    } else {
      ElMessage.error(result.msg || '附件上传失败')
    }
  } catch (error) {
    console.error('手动上传失败:', error)
    ElMessage.error('附件上传失败')
  }
}

// 确认新增
const handleConfirmAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    
    addLoading.value = true
    
    const params: AddOutboundOrderParams = {
      outboundId: 0,
      outboundOrderNumber: addForm.outboundOrderNumber,
      outboundType: addForm.outboundType,
      outboundTime: addForm.outboundTime,
      approval: addForm.approval,
      remarks: addForm.remarks,
      bkThumbnail: addForm.bkThumbnail,
      annex: addForm.annex,
             createdTime: new Date().toISOString(),
      createdBy: 'admin',
      modifiedBy: 'admin',
             modifiedTime: new Date().toISOString(),
             isDelete: false
    }
    
    console.log('新增参数:', params)
    
    const response = await addOutboundOrder(params)
    
    if (response.code === 200) {
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      
      // 刷新数据
      await fetchData(true)
    } else {
      ElMessage.error(response.msg || '新增失败')
    }
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      console.error('新增失败:', error)
      ElMessage.error('新增失败')
    }
  } finally {
    addLoading.value = false
  }
}

// 编辑
const handleEdit = async (row: OutboundOrder) => {
  try {
    // 获取出库单详情
    const response = await getOutboundOrderDetails(row.outboundOrderNumber)
    if (response.code === 200) {
      // 填充编辑表单
      Object.assign(editForm, {
        outboundId: row.outboundId,
        outboundOrderNumber: row.outboundOrderNumber,
        outboundType: row.outboundType,
        outboundTime: row.outboundTime,
        approval: row.approval,
        remarks: row.remarks || '',
        bkThumbnail: row.bkThumbnail || '',
        annex: row.annex || '',
        productDetails: response.data || []
      })
      
      // 打开编辑对话框
      editDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取出库单详情失败')
    }
  } catch (error) {
    console.error('获取出库单详情失败:', error)
    ElMessage.error('获取出库单详情失败')
  }
}

// 确认编辑
const handleConfirmEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    
    editLoading.value = true
    
    // 构建完整的OutboundOrder对象
    const params: OutboundOrder = {
      outboundId: editForm.outboundId,
      outboundOrderNumber: editForm.outboundOrderNumber,
      outboundType: editForm.outboundType,
      outboundTime: editForm.outboundTime,
      approval: editForm.approval || '待审核', // 保持原有审核状态，如果没有则默认为待审核
      remarks: editForm.remarks,
      bkThumbnail: editForm.bkThumbnail,
      annex: editForm.annex,
             createdTime: new Date().toISOString(),
      createdBy: 'admin',
      modifiedBy: 'admin',
             modifiedTime: new Date().toISOString(),
             isDelete: false
    }
    
    console.log('编辑参数:', params)
    
    const response = await updateOutboundOrder(params)
    
    if (response.code === 200) {
      ElMessage.success('编辑成功')
      editDialogVisible.value = false
      
      // 刷新数据
      await fetchData(true)
    } else {
      ElMessage.error(response.msg || '编辑失败')
    }
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message)
  } else {
      console.error('编辑失败:', error)
      ElMessage.error('编辑失败')
    }
  } finally {
    editLoading.value = false
  }
}

// 审核
const handleApprove = (row: OutboundOrder) => {
    approvalForm.outboundId = row.outboundId
    approvalForm.outboundOrderNumber = row.outboundOrderNumber
  approvalForm.approval = ''
  approvalForm.remarks = ''
  approvalForm.modifiedBy = 'admin'
  approvalDialogVisible.value = true
}

// 确认审核
const handleConfirmApproval = async () => {
  if (!approvalForm.approval) {
    ElMessage.warning('请选择审核状态')
    return
  }
  
  approvalLoading.value = true
  try {
                 const params = {
           outboundId: approvalForm.outboundId,
      approval: approvalForm.approval,
           modifiedBy: approvalForm.modifiedBy,
      remarks: approvalForm.remarks
         }
      
    console.log('审核参数:', params)
      
      const response = await updateApprovalStatus(params)
      
    console.log('审核响应:', response)
      
      if (response.code === 200) {
        ElMessage.success('审核成功')
        approvalDialogVisible.value = false
      
      // 立即更新本地数据
      const index = tableData.value.findIndex(item => item.outboundId === approvalForm.outboundId)
      if (index !== -1) {
        tableData.value[index].approval = approvalForm.approval
        console.log('本地数据已更新:', tableData.value[index])
      }
      
      // 强制刷新数据以确保状态正确
      console.log('开始强制刷新数据...')
      await fetchData(true)
      
      // 再次检查更新后的数据
      const updatedIndex = tableData.value.findIndex(item => item.outboundId === approvalForm.outboundId)
      if (updatedIndex !== -1) {
        console.log('刷新后的数据:', tableData.value[updatedIndex])
        if (tableData.value[updatedIndex].approval !== approvalForm.approval) {
          console.warn('警告：刷新后数据状态未更新，可能存在后端问题')
          ElMessage.warning('审核成功，但页面状态可能需要手动刷新')
        }
      }
      } else {
        ElMessage.error(response.msg || '审核失败')
    }
  } catch (error: any) {
    console.error('审核失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    ElMessage.error('审核失败')
  } finally {
    approvalLoading.value = false
  }
}

// 删除
const handleDelete = async (row: OutboundOrder) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除出库单 "${row.outboundOrderNumber}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteOutboundOrder(row.outboundId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection: OutboundOrder[]) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 获取所有出库单产品明细
const fetchAllProductDetails = async () => {
  detailsLoading.value = true
  try {
    const response = await getOutboundProductDetails()
    if (response.code === 200) {
      allProductDetails.value = response.data
      console.log('获取到的所有出库单产品明细:', response.data)
    } else {
      ElMessage.error(response.msg || '获取出库单产品明细失败')
    }
  } catch (error) {
    console.error('获取出库单产品明细失败:', error)
    ElMessage.error('获取出库单产品明细失败')
  } finally {
    detailsLoading.value = false
  }
}

// 明细选择变化
const handleDetailSelectionChange = (selection: OutboundOrderDetail[]) => {
  selectedDetailRows.value = selection
 }

// 明细分页大小变化
const handleDetailSizeChange = (size: number) => {
  detailsPageSize.value = size
  detailsCurrentPage.value = 1
}

// 明细当前页变化
const handleDetailCurrentChange = (page: number) => {
  detailsCurrentPage.value = page
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
  // 获取所有出库单产品明细数据
  fetchAllProductDetails()
})
</script>

<style scoped>
.outbound-order-container {
  padding: 20px;
  background: #f5f5f5;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 自定义滚动条样式 */
.outbound-order-container::-webkit-scrollbar {
  width: 8px;
}

.outbound-order-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.outbound-order-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.outbound-order-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-title h3 {
  margin: 0;
  color: #303133;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 审核对话框样式 */
.approval-dialog {
  border-radius: 8px;
}

.approval-info-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: #f0f9ff;
  border-radius: 4px;
  margin-bottom: 20px;
  color: #409eff;
}

.approval-options {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.approval-label {
  font-weight: bold;
  color: #303133;
}

.approval-radio-group {
    display: flex;
  gap: 20px;
}

.approval-remarks {
  margin-bottom: 20px;
}

.remarks-textarea {
  width: 100%;
}

.approval-footer {
  display: flex;
  justify-content: center;
}

/* 编辑对话框样式 */
.edit-dialog {
  border-radius: 8px;
}

.edit-form {
  padding: 20px 0;
}

.edit-form .el-form-item {
  margin-bottom: 20px;
}

.edit-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 新增对话框样式 */
.add-dialog {
  border-radius: 8px;
}

.add-form {
  padding: 20px 0;
}

.add-form .el-form-item {
  margin-bottom: 20px;
}

.add-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 缩略图上传样式 */
.thumbnail-upload {
  display: inline-block;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 20px;
     text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #909399;
}

.upload-placeholder .el-icon {
  font-size: 24px;
}

/* 附件上传样式 */
.annex-upload {
  display: inline-block;
  margin-right: 10px;
}

.annex-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 10px;
  color: #409eff;
}

/* 产品选择样式 */
.product-selection {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.product-search {
  margin-bottom: 15px;
}

.product-select-dialog {
  border-radius: 8px;
}

.product-select-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* 无图片/附件样式 */
.no-image,
.no-annex {
  color: #909399;
  font-size: 12px;
}

/* 缩略图样式优化 */
.el-table .el-image {
  border: 1px solid #e4e7ed;
  transition: transform 0.3s;
}

.el-table .el-image:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 附件下载按钮样式 */
.annex-download-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 表格中的缩略图容器 */
.thumbnail-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
}

/* 表格中的附件容器 */
.annex-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
}
</style>

